package com.hzbank.aaronkotlin

import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.pdf.PdfRenderer
import android.os.ParcelFileDescriptor
import android.view.LayoutInflater
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.aaron.functionLibs.recycler.BaseViewHolder
import com.aaron.smartktv.XArtBoard
import com.aaron.smartktv.core.tool.XPenType
import com.aaron.smartktv.helper.XArtUtils
import com.hzbank.aaronkotlin.databinding.ActivityDocumentPrewBinding
import com.hzbank.aaronkotlin.databinding.ItemDocumentPrewBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.Dispatcher
import java.io.File

class DocumentPrewActivity: BaseActivity<ActivityDocumentPrewBinding>() {

    private var isPreView: Boolean = true; //true - 预览  false//编辑

    private var inputTextDialog: InputTextDialog? = null

    private var pdfs: MutableList<Bitmap> = mutableListOf()
    private var documentAdapter: DocumentPrewAdapter? = null

    private var pdfRenderer: PdfRenderer? = null;
    private var pfd: ParcelFileDescriptor? = null;

    private var canScoller: Boolean = true

    private var curBoradView: XArtBoard? = null
    private var position: Int = 0

    override fun getBinding(): ActivityDocumentPrewBinding =
        ActivityDocumentPrewBinding.inflate(LayoutInflater.from(this))

    override fun parseView() {

        isPreView = true

        xBing?.docPreview?.layoutManager =
            object : LinearLayoutManager(this@DocumentPrewActivity){

                override fun canScrollVertically(): Boolean {
                    return canScoller
                }
            }

        documentAdapter = DocumentPrewAdapter(LayoutInflater.from(this@DocumentPrewActivity),
            pdfs)

        xBing?.docPreview?.adapter = documentAdapter
        xBing?.docPreview?.setHasFixedSize(true)

        xBing?.hb?.setTextColor(Color.parseColor("#666666"))
        xBing?.xp?.setTextColor(Color.parseColor("#666666"))
        xBing?.qk?.setTextColor(Color.parseColor("#666666"))
        xBing?.bz?.setTextColor(Color.parseColor("#666666"))

        xBing?.hbL?.setOnClickListener {

            isPreView = !isPreView;

            if(isPreView){

                xBing?.hb?.setTextColor(Color.parseColor("#666666"))
                xBing?.xp?.setTextColor(Color.parseColor("#666666"))
                xBing?.qk?.setTextColor(Color.parseColor("#666666"))
                xBing?.bz?.setTextColor(Color.parseColor("#666666"))

                //列表可滑动 预览
                this.canScoller = true

                xBing?.docPreview?.isHandler(true)

                "文档不可编辑".toast(this@DocumentPrewActivity)

            } else {

                xBing?.hb?.setTextColor(Color.parseColor("#1296db"))
                xBing?.xp?.setTextColor(Color.parseColor("#666666"))
                xBing?.qk?.setTextColor(Color.parseColor("#666666"))
                xBing?.bz?.setTextColor(Color.parseColor("#666666"))

                //列表不可滑动 编辑
                this.canScoller = false
                curBoradView = broadRecordMap.get(position)
                curBoradView?.setPenType(XPenType.LINE)

                xBing?.docPreview?.isHandler(false)

                "文档可编辑".toast(this@DocumentPrewActivity)

            }

        }

        xBing?.xpL?.setOnClickListener {

            isPreView = !isPreView;

            if(isPreView){

                xBing?.hb?.setTextColor(Color.parseColor("#666666"))
                xBing?.xp?.setTextColor(Color.parseColor("#666666"))
                xBing?.qk?.setTextColor(Color.parseColor("#666666"))
                xBing?.bz?.setTextColor(Color.parseColor("#666666"))

                //列表可滑动 预览
                this.canScoller = true

                xBing?.docPreview?.isHandler(true)

                "文档不可编辑".toast(this@DocumentPrewActivity)

            } else {

                xBing?.hb?.setTextColor(Color.parseColor("#666666"))
                xBing?.xp?.setTextColor(Color.parseColor("#1296db"))
                xBing?.qk?.setTextColor(Color.parseColor("#666666"))
                xBing?.bz?.setTextColor(Color.parseColor("#666666"))

                //列表不可滑动 编辑
                this.canScoller = false

                curBoradView = broadRecordMap.get(position)
                curBoradView?.setPenType(XPenType.ERASER)

                xBing?.docPreview?.isHandler(false)

                "文档可编辑".toast(this@DocumentPrewActivity)

            }

        }

        xBing?.qkL?.setOnClickListener {

            isPreView = !isPreView;

            if(isPreView){

                xBing?.hb?.setTextColor(Color.parseColor("#666666"))
                xBing?.xp?.setTextColor(Color.parseColor("#666666"))
                xBing?.qk?.setTextColor(Color.parseColor("#666666"))
                xBing?.bz?.setTextColor(Color.parseColor("#666666"))

                //列表可滑动 预览
                this.canScoller = true

                xBing?.docPreview?.isHandler(true)

                "文档不可编辑".toast(this@DocumentPrewActivity)

            } else {

                xBing?.hb?.setTextColor(Color.parseColor("#666666"))
                xBing?.xp?.setTextColor(Color.parseColor("#666666"))
                xBing?.qk?.setTextColor(Color.parseColor("#1296db"))
                xBing?.bz?.setTextColor(Color.parseColor("#666666"))

                //列表不可滑动 编辑
                this.canScoller = false

                curBoradView = broadRecordMap.get(position)
                curBoradView?.reset()

                xBing?.docPreview?.isHandler(false)

                "文档可编辑".toast(this@DocumentPrewActivity)

            }

        }

        xBing?.bzL?.setOnClickListener {

            isPreView = !isPreView;

            if(isPreView){

                xBing?.hb?.setTextColor(Color.parseColor("#666666"))
                xBing?.xp?.setTextColor(Color.parseColor("#666666"))
                xBing?.qk?.setTextColor(Color.parseColor("#666666"))
                xBing?.bz?.setTextColor(Color.parseColor("#666666"))

                //列表可滑动 预览
                this.canScoller = true

                xBing?.docPreview?.isHandler(true)

                "文档不可编辑".toast(this@DocumentPrewActivity)

            } else {

                xBing?.hb?.setTextColor(Color.parseColor("#666666"))
                xBing?.xp?.setTextColor(Color.parseColor("#666666"))
                xBing?.qk?.setTextColor(Color.parseColor("#666666"))
                xBing?.bz?.setTextColor(Color.parseColor("#1296db"))

                //列表不可滑动 编辑
                this.canScoller = false

                this@DocumentPrewActivity.curBoradView = broadRecordMap.get(position)

                inputTextDialog = InputTextDialog(this@DocumentPrewActivity, 200, 300)
                inputTextDialog?.setInputCallback(object : InputTextDialog.Companion.InputCallback{
                    override fun markLabel(label: String) {

                        ("标注内容1="+label).showLog()
                        //绘制
                        this@DocumentPrewActivity.curBoradView?.setMarkLabel(label)

                    }
                })
                //标注
                inputTextDialog?.showLoding()


                xBing?.docPreview?.isHandler(false)

                "文档可编辑".toast(this@DocumentPrewActivity)
            }

        }


        lifecycleScope.launch(Dispatchers.IO) {

            val bmps = loadPdf()

            pdfs.clear()

            pdfs.addAll(bmps)

            withContext(Dispatchers.Main){

                documentAdapter?.notifyDataSetChanged()

            }
        }

        xBing?.docPreview?.addOnScrollListener(object : RecyclerView.OnScrollListener(){

            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {

                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    // 当 RecyclerView 的滑动事件完成（滑动停止）时，会回调到这里
                    val layoutManager: LinearLayoutManager  = xBing?.docPreview?.layoutManager as LinearLayoutManager
                    // 获取当前页面内第一个完整显示的Item，由于我的子Item自动占满页面宽度，所以当前页面内完整显示的第一个Item，就是我所需要的Item
                    position = layoutManager.findFirstVisibleItemPosition()

                    ("列表监听--position2=$position").showLog()

//                    val lastVisibleItemPosition: Int = layoutManager.findLastVisibleItemPosition()
//                    val firstCompletelyVisibleItemPosition: Int = layoutManager.findFirstCompletelyVisibleItemPosition()
//                    val lastCompletelyVisibleItemPosition: Int = layoutManager.findLastCompletelyVisibleItemPosition()
//
//                    ("列表监听--firstVisibleItemPosition=$firstVisibleItemPosition" +
//                            "---lastVisibleItemPosition=$lastVisibleItemPosition").showLog()
//
//                    ("列表监听--firstCompletelyVisibleItemPosition=$firstCompletelyVisibleItemPosition" +
//                            "---lastCompletelyVisibleItemPosition=$lastCompletelyVisibleItemPosition").showLog()

                    // 判断获取的position不为-1，则为有效数据
//                    if ((firstVisibleItemPosition != -1)
//                        && (firstVisibleItemPosition == lastVisibleItemPosition)) {
////                        currentIndex = firstCompletelyVisibleItemPosition;
////                        // 显示当前选项卡的位置（对于用户来讲，当前选项卡的位置为position+1）
////                        String currentLocation = (firstCompletelyVisibleItemPosition + 1) + "";
////                        if (tvCurrent != null) {
////                            tvCurrent.setText(currentLocation);
////                        }
//                        // 获取当前选项卡的viewHolder实例，可以自行做业务逻辑处理
//                        val viewHolder: RecyclerView.ViewHolder? = xBing?.docPreview?.findViewHolderForAdapterPosition(firstVisibleItemPosition)
//                        if(null!=viewHolder){
//
//                            "列表监听--设置当前显示画板".showLog()
//
//                            this@DocumentPrewActivity.curBoradView = viewHolder.itemView.findViewById(R.id.documentPage)
//                        }
//                    }
                }
            }
        })
    }



    suspend fun loadPdf(): MutableList<Bitmap>{

        val docs: MutableList<Bitmap> = mutableListOf()

        val file = File(docFilePath+"test.pdf")

        if(null!=file && file.exists()){

            try {

                pfd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
                pdfRenderer = PdfRenderer(pfd!!);

                docs.clear()

                val pageCount = pdfRenderer?.pageCount

                for(index in 0 until  pageCount!!){

                    var page: PdfRenderer.Page = pdfRenderer?.openPage(index)!!

                    val bmp: Bitmap = Bitmap.createBitmap(page.getWidth(),
                        page.getHeight(), Bitmap.Config.ARGB_8888)

                    page.render(bmp, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
                    page.close();

                    docs.add(bmp)

                }


                return docs

            }catch (e: Exception){
                e.printStackTrace()
            }
        }

        return mutableListOf()

    }

    override fun onDestroy() {
        broadRecordMap?.clear()
        inputTextDialog?.hiddenLoading()
        super.onDestroy()
    }

    companion object{

        var broadRecordMap: MutableMap<Int, XArtBoard> = mutableMapOf()
        val docFilePath = BaseApplication.app.getCacheDir().getAbsolutePath()+ File.separator + "docs" + File.separator

    }


}